var prefix = "/product/data";
$(function() {
	console.info(23);
	load();
});

function renderCategoryThird(obj) {
	var index = obj.options[obj.selectedIndex].value;
	var html = "<option value=''>请选择下级分类</option>";
	if (index == 0) {
		$("#ccate").html(html);
	}else {
		$.ajax({
			url: "/category/manage/getChildByPar",
			data:{"id":index},
			dataType: "json",
			success: function(data){
				for(var i=0; i< data.length; i++){
					html += '<option value="'+data[i].id+'">'+data[i].name+'</option>';
				}
				$("#ccate").html(html);
			}
		})
	}
}

function load() {
	$('#productbaseTable').bootstrapTable({
		method : 'get', // 服务器数据的请求方式 get or post
		url : prefix + "/list", // 服务器数据的加载地址
		showRefresh : true,
		// showToggle : true,
		iconSize : 'outline',
		// toolbar: '#exampleToolbar',
		striped : true, // 设置为true会有隔行变色效果
		dataType : "json", // 服务器返回的数据类型
		pagination : true, // 设置为true会在底部显示分页条
		pageList : [ 10, 20, 50,100,200 ],
		// queryParamsType : "limit",
		// //设置为limit则会发送符合RESTFull格式的参数
		singleSelect : false, // 设置为true将禁止多选
		// contentType : "application/x-www-form-urlencoded",
		// //发送到服务器的数据编码类型
		pageSize : 10, // 如果设置了分页，每页数据条数
		pageNumber : 1, // 如果设置了分布，首页页码
		// search : true, // 是否显示搜索框
		showColumns : true, // 是否显示内容下拉框（选择显示的列）
		sidePagination : "server", // 设置在哪里进行分页，可选值为"client" 或者
		// "server"
		queryParams : function(params) {
			return {
				limit : params.limit,
				offset : params.offset,
				startDate: $.trim($("#startDate").val()),
                endDate: $.trim($("#endDate").val()),
                title:$.trim($("#productName").val()),
                status:$.trim($("#type").val()),
                pcate:$.trim($("#pcate").val()),
                ccate:$.trim($("#ccate").val()),
               /* supplierId:$.trim($("#supply").val()),*/
               /* centreId:$.trim($("#centreId").val()),*/
                upStartTime:$.trim($("#upStartTime").val()),
                upEndTime:$.trim($("#upEndTime").val()),
			};
		},
		 onPostBody: function () {
			/* sumcostprice()*/
	    
	    },
		// //请求服务器数据时，你可以通过重写参数的方式添加一些额外的参数，例如 toolbar 中的参数 如果
		// queryParamsType = 'limit' ,返回参数必须包含
		// limit, offset, search, sort, order 否则, 需要包含:
		// pageSize, pageNumber, searchText, sortName,
		// sortOrder.
		// 返回false将会终止请求
		columns : [
				{
					checkbox : true
				},
				{
					field : 'displayorder', // 列字段名
					title : '排序' // 列标题
				},
				{
					field : 'id', // 列字段名
					title : 'ID' // 列标题
				},
				{
					field : 'title',
					title : '商品标题'
				},
				{
					field : 'thumb',
					title : '商品图片',
					 formatter: function (value, row, index) {
                         return '<img style="width:100px;height:80px" src=' + value + '>';
                     }
				},
				{
					field : 'supplyNm',
					title : '供应商名称'
				},
				{
					field : 'unit',
					title : '单位'
				},
				{
                    field : '',
                    title : '商品属性',
                    formatter : function(value, row, index) {
                        var properties = "";
                        // if (row.iszhicai == 1) {
                        //     properties += '<a title="直采"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'iszhicai\',\'\')">直</button></a>';
                        // } else {
                        //     properties += '<a title="直采"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'iszhicai\',\'\')">直</button></a>';
                        // }
						if(row.productType == 6){
							if (row.isziti == 1) {
								properties += '<a title="自提"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isziti\',\'\')">提</button></a>';
							} else {
								properties += '<a title="自提"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isziti\',\'\')">提</button></a>';
							}
							if (row.istangshi == 1) {
								properties += '<a title="堂食"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'istangshi\',\'\')">堂</button></a>';
							} else {
								properties += '<a title="堂食"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'istangshi\',\'\')">堂</button></a>';
							}
							if (row.iswaimai == 1) {
								properties += '<a title="外卖"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'iswaimai\',\'\')">外</button></a>';
							} else {
								properties += '<a title="外卖"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'iswaimai\',\'\')">外</button></a>';
							}
						}else {
							if (row.isnew == 1) {
								properties += '<a title="新上"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'isnew\',\'\')">新</button></a>';
							} else {
								properties += '<a title="新上"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'isnew\',\'\')">新</button></a>';
							}

							if (row.ishot == 1) {
								properties += '<a title="爆款"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'ishot\',\'\')">爆</button></a>';
							} else {
								properties += '<a title="爆款"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'ishot\',\'\')">爆</button></a>';
							}
							if (row.ismao == 1) {
								properties += '<a title="特卖"><button class="btn btn-xs btn-info pro" onclick="updateProduct(' + row.id + ',\'ismao\',\'\')">特</button></a>';
							} else {
								properties += '<a title="特卖"><button class="btn btn-xs btn-default pro" onclick="updateProduct(' + row.id + ',\'ismao\',\'\')">特</button></a>';
							}
						}
                        // if (row.isfanchang == 1) {
                        //     properties += '<a title="返场"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isfanchang\',\'\')">返</button></a>';
                        // } else {
                        //     properties += '<a title="返场"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isfanchang\',\'\')">返</button></a>';
                        // }
                        /*if (row.isgerida == 1) {
                            properties += '<a title="隔日达"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isgerida\')">隔</button></a>';
                        } else {
                            properties += '<a title="隔日达"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isgerida\')">隔</button></a>';
                        }*/
                        /*if (row.isrecommand == 1) {
                            properties += '<a title="推荐"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isrecommand\')">推</button></a>';
                        } else {
                            properties += '<a title="推荐"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isrecommand\')">推</button></a>';
                        }*/
                        /*if (row.isdiscount == 1) {
                            properties += '<a title="促销"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isdiscount\')">促</button></a>';
                        } else {
                            properties += '<a title="促销"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isdiscount\')">促</button></a>';
                        }*/
                        // if (row.ismiaosha == 1) {
                         //    properties += '<a title="秒杀"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'ismiaosha\',\'\')">秒</button></a>';
                        // } else {
                         //    properties += '<a title="秒杀"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'ismiaosha\',\'\')">秒</button></a>';
                        // }
                        // if (row.islimited == 1) {
                         //    properties += '<a title="限量"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'islimited\',\'\')">限</button></a>';
                        // } else {
                         //    properties += '<a title="限量"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'islimited\',\'\')">限</button></a>';
                        // }
                        //
                        // if (row.isfashi == 1) {
                         //    properties += '<a title="假一罚十"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isfashi\',\'\')">假</button></a>';
                        // } else {
                         //    properties += '<a title="假一罚十"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isfashi\',\'\')">假</button></a>';
                        // }
                        // if (row.iszhutihuakuang == 1) {
                         //    properties += '<a title="主题画框"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'iszhutihuakuang\',\'\')">主</button></a>';
                        // } else {
                         //    properties += '<a title="主题画框"><button class="btn btn-xs btn-default pro"onclick="updateProduct('+row.id+',\'iszhutihuakuang\',\'\')" >主</button></a>';
                        // }
                        // if (row.isbig == 1) {
                        	// properties += '<a title="大件"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isbig\',\'\')">大</button></a>';
                        // } else {
                        	// properties += '<a title="大件"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isbig\',\'\')">大</button></a>';
                        // }
                        // if (row.isvip == 1) {
                         //    properties += '<a title="会员"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isvip\',\'\')">vip</button></a>';
                        // } else {
                         //    properties += '<a title="会员"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isvip\',\'\')">vip</button></a>';
                        // }
						// if (row.isTeamBuy == 1) {
						// 	properties += '<a title="门店采购"><button class="btn btn-xs btn-info pro">团</button></a>';
						// } else {
						// 	properties += '<a title="门店采购"><button class="btn btn-xs btn-default pro" >团</button></a>';
						// }
                        
                        /*if (row.istime == 1) {
                            properties += '<a title="限时卖"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'istime\')">时</button></a>';
                        } else {
                            properties += '<a title="限时卖"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'istime\')">时</button></a>';
                        }
                        
                        if (row.isvip == 1) {
                            properties += '<a title="会员"><button class="btn btn-xs btn-info pro" onclick="updateProduct('+row.id+',\'isvip\')">vip</button></a>';
                        } else {
                            properties += '<a title="会员"><button class="btn btn-xs btn-default pro" onclick="updateProduct('+row.id+',\'isvip\')">vip</button></a>';
                        }*/
                        return properties;
                    }
				},
				{
					field : 'marketprice',
					title : '现价'
				},{
					field : 'costprice',
					title : '成本价'
				},
				{
					field : 'headcommission',
					title : '佣金'
				},
				{
					field : 'salesreal',
					title : '销量'
				}/*,{
					field : 'allcostprice',
					title : '总成本'
				},{
					field : 'lirun',
					title : '总利润'
				}*/,
				{
					field : 'total',
					title : '库存',
					/*formatter: function (value, row, index) {
						var title = row.title;
						var str = '<button class="btn btn-xs btn-warning" onclick="showStockTotal(\''+row.id+'\',\''+title+'\')">'+value+'</button>';
						return str;
                    }*/
				},
				{
					field : 'status',
					title : '状态',
					formatter : function(value, row, index) {
                        if (value == 0) {
                            return "<button class='btn btn-sm btn-success pro' onclick='updateProduct("+row.id+",\"status\")'>下架</button>";
                        }
                        if (value == 1) {
                            return "<button class='btn btn-sm btn-info pro' onclick='updateProduct("+row.id+",\"status\")'>上架</button>";
                        }
                        if (value == 2) {
                            return "<span class='label label-default'>定时上架</span>";
                        }
					}
				},
				{
					field : 'upStartTime',
					title : '上架时间'
				},
				{
					field : 'upEndTime',
					title : '下架时间'
				},
				{
					field : 'timestart',
					title : '开售时间'
				},
				{
					field : 'timeend',
					title : '停售时间'
				},
				{
					title : '操作',
					field : 'id',
					align : 'center',
					formatter : function(value, row, index) {
						var e = '<a class="btn btn-primary btn-sm '
								+ s_edit_h
								+ '" href="#" mce_href="#" title="编辑" onclick="edit(\''
								+ value
								+ '\')"><i class="fa fa-edit"></i>编辑</a> ';

						var d = '<a class="btn btn-warning btn-sm '
								+ s_remove_h
								+ '" href="#" title="删除"  mce_href="#" onclick="remove(\''
								+ value
								+ '\')"><i class="fa fa-remove"></i>删除</a> ';
						var c = '<a class="btn btn-success btn-sm '
							+ s_copy_h
							+ '" href="#" title="复制"  mce_href="#" onclick="copy(\''
							+ value
							+ '\')"><i class="fa fa-edit"></i>复制</a> ';
						return e + d+c;
					}
				} ]
	});
}
function reLoad() {
	$('#productbaseTable').bootstrapTable('refresh');
}
function remove(id) {
	layer.confirm('确定要删除选中的记录？', {
		btn : [ '确定', '取消' ]
	}, function() {
		$.ajax({
			url : prefix + "/remove",
			type : "post",
			data : {
				'id' : id
			},
			beforeSend : function(request) {
				index = layer.load();
			},
			success : function(r) {
				if (r.code == 0) {
					layer.close(index);
					layer.msg(r.msg);
					reLoad();
				} else {
					layer.msg(r.msg);
				}
			}
		});
	})
}

/**
 * 更新商品
 * @param id：商品id
 * @param column：更新的字段
 */
function updateProduct(id, column) {
    $('.pro').attr('disabled', true);
    $.ajax({
        url :'/product/manage/btnUpdate',
        type : 'POST',
        data: {"id" : id, "column" : column},
        success :function(result){
            if (result.code == 0){
                $('#productbaseTable').bootstrapTable('refresh');
            } else {
                layer.alert("更新失败，请联系管理员", {icon: 5});
            }
            $('.pro').attr('disabled', false);
        }
    })
}

function batchRemove() {
	var rows = $('#productbaseTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
	if (rows.length == 0) {
		layer.msg("请选择要删除的数据");
		return;
	}
	layer.confirm("确认要删除选中的'" + rows.length + "'条数据吗?", {
		btn : [ '确定', '取消' ]
	// 按钮
	}, function() {
		var ids = new Array();
		// 遍历所有选择的行数据，取每条数据对应的ID
		$.each(rows, function(i, row) {
			ids[i] = row['centreId'];
		});
		$.ajax({
			type : 'POST',
			data : {
				"ids" : ids
			},
			url : prefix + '/batchRemove',
			success : function(r) {
				if (r.code == 0) {
					layer.msg(r.msg);
					reLoad();
				} else {
					layer.msg(r.msg);
				}
			}
		});
	}, function() {
	});
}

function add() {
	// iframe层
	layer.open({
		id : 'product_add',
		type : 2,
		title : '新增商品',
		maxmin : true,
		shadeClose : false, // 点击遮罩关闭层
		area : [ '60%', '80%' ],
		content : prefix + '/toAdd' // iframe的url
	});
}

function edit(id) {
	layer.open({
		id : 'product_edit',
		type : 2,
		title : '修改商品',
		maxmin : true,
		shadeClose : false,
		area : [ '90%', '90%' ],
		content : prefix + '/edit/' + id, // iframe的url
		end: function () {
			reLoad();
        }
	});
}

function detail(centreId) {
	layer.open({
		id : 'product_detail',
		type : 2,
		title : '商品详情',
		maxmin : true,
		shadeClose : false,
		area : [ '60%', '80%' ],
		content : prefix + '/detail/' + centreId // iframe的url
	});
}

function showStockTotal(id,title){
	$("#productTitle").text(title);
	$("#productId").val(id);
    $("#modal-teams").modal();
}

/*// 修改库存
function updateTotal() {
	var total = $("#total").val();
	var id = $("#productId").val();
	$.ajax({
        url :'/product/data/updateTotal',
        type : 'POST',
        data: {"id" : id, "total" : total},
        success :function(result){
            if (result.code == 0){
                $('#productbaseTable').bootstrapTable('refresh');
                var Modal=$('#modal-teams');
            	Modal.modal('hide');
            	$('.modal-backdrop').remove();
            } else {
            	if (result.msg != null || result.msg != '') {
            		layer.alert(result.msg, {icon: 5});
            	} else {
            		layer.alert("更新失败，请联系管理员", {icon: 5});
            	}
                
            }
        }
	})
}*/

function inport() {
	var formData = new FormData();
    var name = $("#excelFile").val();
    if (name == null || name == '') {
    	layer.msg("请选择文件需要上传的文件", {icon:7});
    	return;
    }
    formData.append("file",$("#excelFile")[0].files[0]);
    formData.append("name",name);//这个地方可以传递多个参数
    $.ajax({
        url :  '/product/data/importExcel',
        type : 'POST',
        async : false,
        data : formData,
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        beforeSend:function(){
            console.log("正在进行，请稍候");
        },
        success : function(responseStr) {
            if(responseStr.code == 0) {
                layer.msg("导入成功");
                reLoad();
            } else {
            	layer.msg(responseStr.msg);
            	//layer.msg("导入失败，请联系管理员");
            }
        }
    });
}


/**
 * 导出
 */
function exportProduct() {
	var startDate= $.trim($("#startDate").val());
	var endDate = $.trim($("#endDate").val());
	var  title = $.trim($("#productName").val());
	var status = $.trim($("#type").val());
	var pcate = $.trim($("#pcate").val());
	var ccate = $.trim($("#ccate").val());
	var supplierId = $.trim($("#supply").val());
	var centreId =  $("*[name='centreId']").val();
	var upStartTime = $.trim($("#upStartTime").val());
	var upEndTime = $.trim($("#upEndTime").val());
	if(upStartTime==null || upStartTime =='' || upEndTime==null || upEndTime==''){
		  layer.msg("请选择时间");
	      return;
	}
    window.location.href = prefix + "/exportProduct?startDate="+startDate+ "&endDate="+endDate 
    +"&title="+ title +"&status=" + status+"&pcate="+pcate+"&ccate="+ccate+"&supplierId="+supplierId
    +"&centreId="+centreId+"&upStartTime="+upStartTime+"&upEndTime="+upEndTime;
}

/*function updateSales(){
	  var rows = $('#productbaseTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
	  var sales = $("#sales").val();
	  if(sales==null||sales==''){
		  layer.msg("请输入数量");
	        return;
	  }
	    if (rows.length == 0) {
	        layer.msg("请选择要更新的数据");
	        return;
	    }
	    layer.confirm("确认要更新选中的'" + rows.length + "'条数据吗?", {
	        btn: ['确定', '取消']
	        // 按钮
	    }, function () {
	        var ids = [];
	        // 遍历所有选择的行数据，取每条数据对应的ID
	        $.each(rows, function (i, row) {
	            ids[i] = row['id'];
	        });
	        $.ajax({
	            type: 'POST',
	            data: {
	                "ids": ids,
	                "sales":sales
	            },
	            url: prefix + '/batchUpdateSales',
	            success: function (r) {
	            	$('#modal-sales').modal('hide');
	                if (r.code == 0) {
	                    layer.msg(r.msg);
	                    reLoad();
	                } else {
	                    layer.msg(r.msg);
	                }
	            }
	        });
	    }, function () {
	    });
	
}*/

function copy(id) {
	layer.confirm('确定要复制选中的记录？', {
		btn : [ '确定', '取消' ]
	}, function() {
		$(".layui-layer-btn0").hide();
		//防止重复点击
    	layer.open({type:1,title:false,closeBtn:false}) 
    	var index2 = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
		$.ajax({
			url : prefix + "/copy",
			type : "post",
			data : {
				'id' : id
			},
			beforeSend : function(request) {
				index = layer.load();
			},
			success : function(r) {
				if (r.code == 0) {
					layer.close(index);
					layer.closeAll();
					layer.msg(r.msg);
					reLoad();
				} else {
					layer.msg(r.msg);
				}
			}
		});
	})
}

function batchCopy() {
	var rows = $('#productbaseTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
	if (rows.length === 0) {
		layer.msg("请选择要复制的数据");
		return;
	}
	layer.confirm("确认要复制选中的'" + rows.length + "'条数据吗?", {
		btn: ['确定', '取消']
		// 按钮
	}, function () {
		var ids = [];
		// 遍历所有选择的行数据，取每条数据对应的ID
		$.each(rows, function (i, row) {
			ids[i] = row['id'];
		});
		$.ajax({
			type: 'POST',
			data: {
				"ids": ids
			},
			url: prefix + '/copyBatch',
			success: function (r) {
				if (r.code === 0) {
					layer.msg(r.msg);
					reLoad();
				} else {
					layer.msg(r.msg);
				}
			}
		});
	}, function () {
	});
}

function sumcostprice(){
	var startDate= $.trim($("#startDate").val());
	var endDate = $.trim($("#endDate").val());
	var  title = $.trim($("#productName").val());
	var status = $.trim($("#type").val());
	var pcate = $.trim($("#pcate").val());
	var ccate = $.trim($("#ccate").val());
	var supplierId = $.trim($("#supply").val());
	var centreId =  $("*[name='centreId']").val();
	var upStartTime = $.trim($("#upStartTime").val());
	var upEndTime = $.trim($("#upEndTime").val());
    $.ajax({
		url: prefix+"/sumcostprice",
		data:{"startDate":startDate,"endDate":endDate,"title":title,"status":status, "pcate":pcate,"ccate":ccate,"supplierId":supplierId,"centreId":centreId,"upStartTime":upStartTime,"upEndTime":upEndTime},
		dataType: "json",
		type:"POST",
		success: function(data){
			 
			if(data){
				$("#sumcostprice").html(data.sumcostprice+"元");
				$("#sumlirun").html(data.sumlirun+"元");
				
			}else{
				$("#sumcostprice").html("0 元");
				$("#sumlirun").html("0元");
			}
		}
	})
	
}
